package com.translator.module;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.translator.Constants;
import com.youdao.sdk.app.Language;
import com.youdao.sdk.app.LanguageUtils;
import com.youdao.sdk.ydonlinetranslate.TranslateErrorCode;
import com.youdao.sdk.ydonlinetranslate.TranslateListener;
import com.youdao.sdk.ydonlinetranslate.TranslateParameters;
import com.youdao.sdk.ydonlinetranslate.Translator;
import com.youdao.sdk.ydtranslate.Translate;

/**
 * Created by moker on 2017/10/23.
 */

public class OnlineTranslateModule extends ReactContextBaseJavaModule {


    public OnlineTranslateModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }


    /**
     * 在线翻译
     * @param from  原语言
     * @param to    译语言
     * @param content  翻译内容
     * @param promise  返回
     */
    @ReactMethod
    public void onlineTranslate(String from, String to, String content, final Promise promise){
        Language langFrom = LanguageUtils.getLangByName(from);
        Language langTo = LanguageUtils.getLangByName(to);

        TranslateParameters tps = new TranslateParameters.Builder()
                .source("ydtranslate-demo")
                .from(langFrom).to(langTo).build();

        Translator translator = Translator.getInstance(tps);

        translator.lookup(content, new TranslateListener() {
            @Override
            public void onError(TranslateErrorCode translateErrorCode) {
                promise.reject("-1",translateErrorCode.getCode()+"");
            }

            @Override
            public void onResult(Translate translate, String s) {
                promise.resolve(translate.getTo());
            }
        });



    }





    @Override
    public String getName() {
        return Constants.ONLINE_TRANSLATE;
    }
}
